package cn.fl.warrant.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysOrgApiService;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.dto.SysOrgDTO;
import cmm.user.facade.system.dto.SysUsrDTO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.warrant.service.IArcApplyMainService;
import cn.fl.warrant.transform.ArcApplyMainVOTransform;
import cn.fl.warrant.transform.ArcSysFlowSHVOTransform;
import cn.fl.warrant.vo.ArcApplyMainVO;
import cn.fl.warrant.vo.ArcSysFlowSHVO;

import com.alibaba.fastjson.JSON;

import fl.flow.facade.flow.api.IFlowApiService;
import fl.flow.facade.flow.condition.SysFlowSHQueryCondition;
import fl.flow.facade.flow.constant.FlowConstant;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import fl.flow.facade.flow.dto.FlowStartedDTO;
import fl.flow.facade.flow.dto.SysFlowSHDTO;
import fl.warrant.facade.archive.api.IArcApplyMainApiService;
import fl.warrant.facade.archive.condition.ArcApplyMainQC;
import fl.warrant.facade.archive.constant.ArchiveConstants;
import fl.warrant.facade.archive.dto.ArcApplyMainDTO;

/**
 * @Description: 归档申请主表(旧表：T_API_DOCUMENT_DOSSIERAPPLY) 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class ArcApplyMainServiceImpl implements IArcApplyMainService {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(IArcApplyMainService.class);
	
	/**
	 * TODO 自定义 API 暴露服务
	 */
	@Autowired
	private IArcApplyMainApiService arcApplyMainApiService;
    /**
     * 流程服务
     */
    @Autowired
    private IFlowApiService flowApiService;
    @Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
    @Autowired
    private ISysUsrApiService sysUsrApiService;
    @Autowired
	private ISysOrgApiService sysOrgApiService;// 组织机构
	@Override
	public ArcApplyMainVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "selectById", "主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		//TODO 业务逻辑
		ArcApplyMainDTO dto = this.arcApplyMainApiService.selectById(id);
		
		return ArcApplyMainVOTransform.toVO(dto);
	}

	@Override
	public Long add(ArcApplyMainVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "add", "新增对象不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		//return this.arcApplyMainApiService.add(ArcApplyMainVOTransform.toDTO(entity));
		//TODO 业务逻辑
		return null;
	}

	@Override
	public boolean removeById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "removeById", "删除主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		return this.arcApplyMainApiService.removeById(id);
		
	}
	
	/**
     * 删除
     * @param ids
     * @return
     */
    public boolean removeByIds(List<Long> ids)throws BaseException{
    	if(CollectionUtils.isEmpty(ids)){
    		BaseLogUtils.info(logger, "removeByIds", "删除主键参数集合不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		};
		return false;
    }

	@Override
	public boolean modify(ArcApplyMainVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "modify", "修改对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		return this.arcApplyMainApiService.modify(ArcApplyMainVOTransform.toDTO(entity));
		
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page)page = new Pager();
		return this.arcApplyMainApiService.searchListPage(page);
		
	}

	@Override
	public  DataResultDTO addFlowStart(Map map) throws BaseException {
		DataResultDTO result = new DataResultDTO(BaseExceptionConstant.BASE_EXCEPTION_CODE_200,
				SysLogConstant.LOG_CMM_OPERATE_SUCC);
		String id=(String)map.get("id");
		if (StringUtils.isEmpty(id)) {
			result.setCode(BaseExceptionConstant.BASE_EXCEPTION_CODE_405);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "addFlowStart",
					SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY,
					CurrentThreadContext.getCurrentUserName());
			return result;
		}
		FlowStartParamsDTO flowStartParamsDTO = new FlowStartParamsDTO();
		try {
			// 流程定义Key和流程定义ID 如果是前端选择的则直接指定,如果不是则系统自动按照配置选择唯一一条记录,如果找不到会提示
			flowStartParamsDTO.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_IN);
			flowStartParamsDTO
					.setWordsInTheTable(ArchiveConstants.FLOW_BUSINESS_TYP_ARC);
//			flowStartParamsDTO.setProcDefKey(procDefKey);
//			flowStartParamsDTO.setProcDefId(procDefId);
//			flowStartParamsDTO.setProcNo(procNo);
//			map.put("currentUser", CurrentThreadContext.getCurrentUserId());
			flowStartParamsDTO.setCrtUsrId(CurrentThreadContext
					.getCurrentUserId());
			flowStartParamsDTO.setBusinessKey(id);
			flowStartParamsDTO.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
			flowStartParamsDTO.setSysCd(CurrentThreadContext.getCurrentSysCd());
			flowStartParamsDTO.setBuOrgCd(CurrentThreadContext
					.getCurrentBuOrgCd());
			flowStartParamsDTO.setInitiator(String.valueOf(CurrentThreadContext
					.getCurrentUserId()));
			flowStartParamsDTO.setInitiatorNm(CurrentThreadContext
					.getCurrentUserName());
			flowStartParamsDTO
					.setProcPriority(FlowConstant.FLOW_PRIORITY_EMERGENCY);// 优先级,可以在界面定义
			flowStartParamsDTO
					.setBusinessType(ArchiveConstants.FLOW_MODEL_TYP_ARC_APPLY);// TODO
																					// 确认用不用
			flowStartParamsDTO.setModelTyp(ArchiveConstants.FLOW_MODEL_TYP_ARC_APPLY);// 需要和流程配置中的模块类型匹配
			flowStartParamsDTO.setSearchDesc((String)map.get("keyword"));
			// flowStartParamsDTO.setOrgShtNm(CurrentThreadContext.getCurrentOrgShtNm());
			flowStartParamsDTO.setCstNm((String)map.get("cstNm"));
			flowStartParamsDTO.setStartParams(map);
			BaseLogUtils.info(logger, "addFlowStart", "===发起流程Start===参数:" + JSON.toJSONString(flowStartParamsDTO));
            result = this.flowApiService.noTransFlowStart(flowStartParamsDTO);
            BaseLogUtils.info(logger, "addFlowStart", "===发起流程End===结果:" + JSON.toJSONString(result));

			if (null != result && null != result.getData()) {
				FlowStartedDTO flowStartedDTO = (FlowStartedDTO) result
						.getData();
				if (StringUtils
						.isNotBlank(flowStartedDTO.getNextOperUsrNames())) {
					result.setInfo("下一个节点操作人:"
							+ flowStartedDTO.getNextOperUsrNames());
				} else {
					result.setInfo("流程发起成功");
				}
			}
			
		} catch (BaseException e) {
			result.setCode(BaseExceptionConstant.BASE_EXCEPTION_CODE_405);
			result.setInfo(e.getMessage());
			logger.info(e.getMessage());
		} catch (Exception e) {
			result.setCode(BaseExceptionConstant.BASE_EXCEPTION_CODE_405);
			result.setInfo("系统错误,请联系管理员！");
			logger.error("系统错误,请联系管理员！" + e.getMessage());
		}
		return result;
		
	}
	/**
	 * 查找归档申请流程
	 */
	@Override
	public List<ArcSysFlowSHVO> searchApplyFlow(ArcApplyMainQC condition) throws BaseException{
//		ArcApplyMainQC condition=new ArcApplyMainQC();
//		condition.setContractNo(contractNo);
		if(null == condition){
			BaseLogUtils.error(logger, "searchApplyFlow", "参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		try {
			Pager page=new Pager();
			page.setEveryPage(10000);
			page.setCurrentPage(0);
			page.setCondition(condition);
			page=this.arcApplyMainApiService.searchListPage(page);
			List<ArcApplyMainDTO> list = (List<ArcApplyMainDTO>) page.getResultList();
			List<SysFlowSHDTO> searchList=new ArrayList<SysFlowSHDTO>();
			if (list!=null) {
				for (int i = 0; i < list.size(); i++) {
					SysFlowSHQueryCondition qc = new SysFlowSHQueryCondition();
					qc.setSysCd(CurrentThreadContext.getCurrentSysCd());//系统代码
					qc.setWordsInTheTable(ArchiveConstants.ARC_FLOW_S_H_ARC);//表中字
					qc.setDataId(list.get(i).getId());//业务主键
					//qc.setpDefKey(flowCompleteParamsDTO.getProcDefKey());
					qc.setStatus(BaseConstant.IS_YESNO_YES);
					List<SysFlowSHDTO> sList = this.flowApiService.searchFlowSHDTOList(qc);
					searchList.addAll(sList);
				}
			}
			List<ArcSysFlowSHVO> rList=ArcSysFlowSHVOTransform.toVOList(searchList);
			for (int i = 0; i <rList.size(); i++) {
				ArcSysFlowSHVO vo=rList.get(i);
				List<KeyValueVO>  list1= this.sysDictionaryApiService.getKvList(ArchiveConstants.FLOW_STATUS, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
				if (StringUtils.isBlank(vo.getAudStsCdNm())&&StringUtils.isNotBlank(vo.getAudStsCd())) {
					for (int j = 0; j <list1.size(); j++) {
						if (vo.getAudStsCd().equals(list1.get(j).getKey())) {
							vo.setAudStsCdNm(list1.get(j).getValue());
						}
					}
				}
				if (vo.getCrtUsrId()!=null) {
					SysUsrDTO dto=this.sysUsrApiService.selectSysUsrById(vo.getCrtUsrId(), CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
					if (dto!=null) {
						vo.setCrtUsrIdNm(dto.getUsrNm());
					}
				}
			}
			return rList;
			
		} catch (Exception e) {
			// TODO: handle exception
			BaseLogUtils.error(logger, "searchApplyFlow", "系统错误"+e.getMessage(), CurrentThreadContext.getCurrentUserName());
			return null;
		}
	}
	/**
	 * 生成档案袋编号flag 1 省2总部
	 * @param ArcApplyMainVO flag
	 * @return
	 * @throws BaseException
	 * 2018年4月2日 
	 * lxb
	 */
	@Override
	public String createPortfolioNumber(ArcApplyMainVO vo,String flag) throws BaseException{
		
		return this.arcApplyMainApiService.createPortfolioNumber(ArcApplyMainVOTransform.toDTO(vo), flag);
	}
	@Override
	public List<ArcApplyMainVO> selectList(ArcApplyMainQC qc) {
		if(null == qc) return null;
		return ArcApplyMainVOTransform.toVOList(this.arcApplyMainApiService.searchList(qc));
	}
}
